﻿using Microsoft.Extensions.Logging;
using Model.Dao;
using Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.impl
{
    public class LoginInfoServiceImpl : LoginInfoService
    {
        private readonly ILogger<LoginInfoServiceImpl> _logger;
        private readonly LoginInfoDao loginInfoDao;
        public LoginInfoServiceImpl(LoginInfoDao loginInfoDao) {
            this.loginInfoDao = loginInfoDao;
        }

        /**
         * 通过用户id获取用户登录信息
         * @param userId
         * @return
         */
        public LoginInfo getLoginInfoByUserId(long userId)
        {
            return loginInfoDao.selectLoginInfoByUserId(userId);
        }

        /**
         * 更新登录信息
         * @param loginInfo
         * @param userId
         * @param loginFlag
         * @throws Exception
         */
        public void updateLoginInfo(LoginInfo loginInfo, long userId, bool loginFlag)
        {
            // 如果没有登录信息就插入
            if (loginInfo == null)
            {
                loginInfo= new LoginInfo();
                loginInfo.user_id = userId;
                loginInfo.login_time = DateTime.Now;
                loginInfo.version = 0;
                loginInfo.login_state = CommonConstants.LOGIN;
                // 插入数据
                loginInfoDao.insertLoginInfo(loginInfo);
                
            } 
            else // 如果有登录信息就更新登录信息
            {
                // 如果是登录，那么更新登录状态
                if (loginFlag)
                {
                    loginInfo.login_state = CommonConstants.LOGIN;
                    loginInfo.login_time = DateTime.Now;
                }
                else // 如果是登出，那么更新为登出状态
                {
                    loginInfo.login_state = CommonConstants.LOGOUT;
                    loginInfo.version = loginInfo.version + 1;
                }
                // 更新数据
                loginInfoDao.updateLoginInfo(loginInfo);
            }
        }
    }
}
